//
//  DateFormatterPool.swift
//  NetEaseMusic
//
//  Created by SAGESSE on 2020/3/12.
//  Copyright © 2020 SAGESSE. All rights reserved.
//

import UIKit

class DateFormatterPool {
    
    static let shared: DateFormatterPool = .init()
    
    
    func dateFormat(_ template: String) -> DateFormatter {
        
        let key = "key-\(template)" as NSString
        if let formatter = cache.object(forKey: key) {
            return formatter
        }
        
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh-CN")
        formatter.dateFormat = template
        cache.setObject(formatter, forKey: key)
        return formatter
    }
    
    func localizedDateFormat(_ template: String) -> DateFormatter {
        
        let key = "template-\(template)" as NSString
        if let formatter = cache.object(forKey: key) {
            return formatter
        }
        
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh-CN")
        formatter.setLocalizedDateFormatFromTemplate(template)
        cache.setObject(formatter, forKey: key)
        return formatter
    }
    
    let cache: NSCache<NSString, DateFormatter> = .init()
}
 

extension DateFormatter {
    
    static func string(fromSent date: Date) -> String {
        let now = Date()
        let calendar = Calendar.current
        switch date {
        case _ where calendar.isDateInToday(date):
            return DateFormatterPool.shared.dateFormat("HH:mm").string(from: date)
            
        case _ where calendar.isDateInYesterday(date):
            return DateFormatterPool.shared.dateFormat("'昨天' HH:mm").string(from: date)
            
        case _ where calendar.isDateInTomorrow(date):
            return DateFormatterPool.shared.dateFormat("'明天' HH:mm").string(from: date)
            
        case _ where calendar.compare(date, to: now, toGranularity: .minute) == .orderedSame:
            return "Just"
            
        case _ where calendar.compare(date, to: now, toGranularity: .year) == .orderedSame:
            return DateFormatterPool.shared.localizedDateFormat("MMM-d").string(from: date)
            
        default:
            return DateFormatterPool.shared.localizedDateFormat("yyyy-MMM-d").string(from: date)
        }
    }
}


